package com.jader.myviews;

import java.util.List;

import com.google.gson.Gson;
import com.jader.activities.OrderActivity;
import com.jader.activities.ShopCartActivity;
import com.jader.beans.ShopCartGoods;
import com.jader.beans.User;
import com.jader.util.JaderApplication;
import com.jader.util.MD5Tool;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.zlp.jader.R;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.PopupWindow.OnDismissListener;

public class ShopcatPopWindow implements OnDismissListener, OnClickListener {

	private ImageView cancel_buy;
	private PopupWindow popupWindow;
	private OnItemClickListener listener;
	private Context context;
	private View view;
	private TextView payment_user, payment_price;
	private Button confirm_payment;
	private double price;
	private HttpUtils httpUtils;
	private String url = JaderApplication.getIP() + "/Jader/client?type="
			+ JaderApplication.SELECT_USERBYID + "&userid=";
	private String pay_url = JaderApplication.getIP() + "/Jader/client";
	private User user;
	private ShopCartActivity buyNow;
	private EditText text;
	private AlertDialog alertDialog;
	private RequestParams params;
	private Gson gson;
	private MyProgressDialog dialog;
	private List<ShopCartGoods> goods;
	private int addressid;

	public ShopcatPopWindow(Context context) {
		this.context = context;
		buyNow = (ShopCartActivity) context;
		httpUtils = new HttpUtils();
		gson = new Gson();
		view = LayoutInflater.from(this.context).inflate(R.layout.pop_payment,
				null);
		cancel_buy = (ImageView) view.findViewById(R.id.cancel_buy);
		payment_user = (TextView) view.findViewById(R.id.payment_user);
		payment_price = (TextView) view.findViewById(R.id.payment_price);
		confirm_payment = (Button) view.findViewById(R.id.confirm_payment);
		cancel_buy.setOnClickListener(this);
		confirm_payment.setOnClickListener(this);
		popupWindow = new PopupWindow(view, LayoutParams.MATCH_PARENT,
				LayoutParams.WRAP_CONTENT);
		// popupWindow.setBackgroundDrawable(new
		// ColorDrawable(Color.TRANSPARENT));
		popupWindow.setBackgroundDrawable(null);
		popupWindow.setOnDismissListener(this);
		popupWindow.setAnimationStyle(R.style.AnimationFade);
		view.setFocusableInTouchMode(true);
		OnKeyListenerImp keyListenerImp = new OnKeyListenerImp();
		view.setOnKeyListener(keyListenerImp);
	}

	private class OnKeyListenerImp implements OnKeyListener {

		@Override
		public boolean onKey(View arg0, int arg1, KeyEvent arg2) {
			view.setOnKeyListener(null);
			if (arg1 == KeyEvent.KEYCODE_BACK && arg0 == view) {
				new AlertDialog.Builder(ShopcatPopWindow.this.context)
						.setTitle("取消支付？")
						.setMessage("您确定要取消此次支付吗？")
						.setPositiveButton("取消支付",
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface arg0,
											int arg1) {
										ShopcatPopWindow.this.pay_return();
									}
								})
						.setNegativeButton("继续支付",
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface arg0,
											int arg1) {
										view.setOnKeyListener(new OnKeyListenerImp());
									}
								}).show();
				return true;
			}
			return false;
		}

	}

	public interface OnItemClickListener {
		public void onClickOKPop();
	}

	public void dissmiss() {
		popupWindow.dismiss();
	}

	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.cancel_buy:
			new AlertDialog.Builder(context)
					.setTitle("取消支付？")
					.setMessage("您确定要取消此次支付吗？")
					.setPositiveButton("取消支付",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface arg0,
										int arg1) {
									ShopcatPopWindow.this.pay_return();
								}
							})
					.setNegativeButton("继续支付",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface arg0,
										int arg1) {

								}
							}).show();
			break;
		case R.id.confirm_payment:
			View view = LayoutInflater.from(context).inflate(
					R.layout.payment_dialog, null);
			text = (EditText) view.findViewById(R.id.pay_put_in_password);
			alertDialog = new AlertDialog.Builder(context)
					.setTitle("请输入密码：")
					.setView(view)
					.setPositiveButton("确认支付",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface arg0,
										int arg1) {
								}
							})
					.setNegativeButton("取消支付",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface arg0,
										int arg1) {

								}
							}).show();
			alertDialog.setCanceledOnTouchOutside(false);
			alertDialog.getButton(AlertDialog.BUTTON_POSITIVE)
					.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View arg0) {
							String password = text.getText().toString().trim();
							if (password == null || "".equals(password)) {
								alertDialog.show();
								JaderApplication.show(context, "请输入密码确认支付");
							} else {
								String md5_password = MD5Tool.MD5(password);
								if (md5_password.equals(user.getPassword())) {
									if (user.getMoney() < price) {
										JaderApplication
												.show(context, "账户余额不足");
									} else {
										params = new RequestParams();
										params.addBodyParameter(
												"type",
												""
														+ JaderApplication.INSERT_ORDER_FROM_SHOPCART);
										params.addBodyParameter("addressid",
												addressid + "");

										params.addBodyParameter("shopcart",
												new Gson().toJson(goods));
										payOrder(pay_url, params);
									}
								} else {
									alertDialog.show();
									JaderApplication.show(context, "密码输入错误");
								}

							}
						}
					});
			break;

		default:
			break;
		}
	}

	public boolean isShowing() {
		return popupWindow.isShowing();
	}

	@Override
	public void onDismiss() {
		listener.onClickOKPop();
	}

	public void showAsDropDown(View parent) {
		dialog = JaderApplication.getMyDialog(context);
		dialog.show();
		sendRequest(url + goods.get(0).getShopcart().getUserid());
		popupWindow.showAtLocation(parent, Gravity.BOTTOM, 0, 0);
		popupWindow.setFocusable(true);
		popupWindow.setOutsideTouchable(true);
		popupWindow.update();
	}

	public void setOnItemClickListener(OnItemClickListener listener) {
		this.listener = listener;
	}

	public void payment(List<ShopCartGoods> goods, int addressid) {
		this.addressid = addressid;
		this.goods = goods;
		price = 0;
		for (int i = 0; i < goods.size(); i++) {
			price += goods.get(i).getGoods().getPrice()
					* goods.get(i).getShopcart().getNumber();
		}
	}

	private void intData() {
		payment_user.setText(user.getUsername());
		payment_price.setText(JaderApplication.getPrice(price) + "元");
	}

	private void sendRequest(String url) {
		httpUtils.send(HttpMethod.GET, url, new RequestCallBack<String>() {

			@Override
			public void onFailure(HttpException arg0, String arg1) {
				if (dialog.isShowing()) {
					dialog.dismiss();
				}
			}

			@Override
			public void onSuccess(ResponseInfo<String> arg0) {
				user = gson.fromJson(arg0.result, User.class);
				intData();
				if (dialog.isShowing()) {
					dialog.dismiss();
				}
			}

		});
	}

	private void payOrder(String url, RequestParams params) {
		httpUtils.send(HttpMethod.POST, url, params,
				new RequestCallBack<String>() {
					@Override
					public void onFailure(HttpException arg0, String arg1) {
						pay_return();
						JaderApplication.show(context, "访问网络失败");
					}

					@Override
					public void onSuccess(ResponseInfo<String> arg0) {
						String result = arg0.result;
						if (!JaderApplication.isEmpty(result)
								&& "true".equals(result)) {
							user.setMoney(user.getMoney() - price);
							JaderApplication.show(context, "支付成功");

							Intent intent = new Intent(buyNow,
									OrderActivity.class);
							buyNow.startActivity(intent);
							buyNow.finish();
						} else {
							JaderApplication.show(context, "支付失败，请重试！");
						}
						pay_return();
					}
				});
	}

	private void pay_return() {
		if (alertDialog != null && alertDialog.isShowing()) {
			alertDialog.dismiss();
		}
		popupWindow.dismiss();
		listener.onClickOKPop();
	}

}
